<template>
  <div class="dimension-config-container">
    <!-- 页面标题与操作按钮 -->
    <div class="page-header">
      <h1 class="page-title">
        <i class="fa fa-cubes text-primary mr-2"></i>
        维度配置
      </h1>
      <div class="header-actions">
        <!-- <el-button
          type="primary"
          :icon="Plus"
          @click="handleCreateDimension"
          :loading="actionLoading"
        >
          创建维度
        </el-button> -->
        <el-button
          type="default"
          :icon="Refresh"
          @click="handleRefresh"
          :loading="actionLoading"
        >
          刷新
        </el-button>
        <!-- <el-dropdown
          v-if="selectedRows.length > 0"
          @command="handleBatchCommand"
        >
          <el-button type="default">
            批量操作 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="enable"> 批量启用 </el-dropdown-item>
              <el-dropdown-item command="disable"> 批量禁用 </el-dropdown-item>
              <el-dropdown-item command="delete" divided>
                <span class="text-danger">批量删除</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          type="default"
          @click="toggleSortMode"
          :loading="actionLoading"
          :class="{ 'sort-mode-active': sortMode }"
        >
          {{ sortMode ? "退出排序模式" : "排序模式" }}
        </el-button> -->
      </div>
    </div>

    <!-- 维度统计卡片 -->
    <StatisticsCards :statistics="statistics" :loading="statsLoading" />

    <!-- 筛选区 -->
    <FilterPanel
      :form-data="filterForm"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 排序模式提示 -->
    <!-- <div v-if="sortMode" class="sort-mode-notice">
      <el-alert
        title="排序模式已启用 - 拖动序号列可重新排序"
        type="info"
        :closable="false"
        show-icon
      ></el-alert>
      <div class="sort-mode-actions">
        <el-button type="default" size="small" @click="handleCancelSort">
          撤销更改
        </el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleSaveSort"
          :loading="actionLoading"
        >
          保存排序
        </el-button>
      </div>
    </div> -->

    <!-- 待保存排序变更 -->
    <!-- <el-card
      v-if="sortMode && sortChanges.length > 0"
      class="sort-changes-card"
    >
      <div class="card-title">待保存的更改</div>
      <div class="changes-list">
        <div
          v-for="(change, index) in sortChanges"
          :key="index"
          class="change-item"
        >
          • {{ change.name }}: 位置 {{ change.oldIndex }} →
          {{ change.newIndex }}
        </div>
      </div>
      <div class="auto-save-info">
        <el-switch
          v-model="autoSaveSort"
          active-text="自动保存已开启"
          inactive-text="自动保存已关闭"
          size="small"
        ></el-switch>
        <el-button
          v-if="!autoSaveSort"
          type="text"
          size="small"
          @click="handleSaveSort"
        >
          手动保存
        </el-button>
      </div>
    </el-card> -->

    <!-- 维度列表表格 -->
    <DimensionTable
      ref="dimensionTableRef"
        :data="dimensionList"
        :loading="tableLoading"
      :pagination="pagination"
      selection-type="none"
      @size-change="handleSizeChange"
      @current-page-change="handlePageChange"
      @view-detail="handleViewDetail"
      @edit="handleEditDimension"
      @enable="handleEnableDimension"
      @disable="handleDisableDimension"
      @delete="handleDeleteDimension"
      @handleCreateDimension="handleCreateDimension"
    />

    <!-- 创建/编辑维度对话框 -->
    <CreateEditDimensionDialog
      v-model="showCreateEditDialog"
      :dimension-id="currentDimensionId"
      :dimension-data="currentDimension"
      :is-edit="!!currentDimensionId"
      :loading="detailLoading"
      @success="handleFormSuccess"
    />

    <!-- 维度详情对话框 -->
    <DimensionDetailDialog
      v-model="showDetailDialog"
      :dimension-id="currentDimensionId"
      :dimension-data="currentDimension"
      :loading="detailLoading"
      @view-usage="handleViewUsage"
      @copy="handleCopyFromDetail"
    />

    <!-- 复制维度对话框 -->
    <CopyDimensionDialog
      v-model="showCopyDialog"
      :source-dimension-id="String(currentDimensionId)"
      @success="handleCopySuccess"
    />

    <!-- 批量操作确认对话框 -->
    <BatchOperationDialog
      v-model="showBatchConfirmDialog"
      :operation="batchOperation"
      :items="selectedRows"
      @confirm="handleBatchConfirm"
    />

    <!-- 批量操作结果对话框 -->
    <BatchResultDialog
      v-model="showBatchResultDialog"
      :result="batchResult"
      @retry-failed="handleRetryFailed"
    />

    <!-- 使用情况查询结果对话框 -->
    <DimensionUsageDialog
      v-model="showUsageDialog"
      :dimension-code="currentDimensionCode"
    />

    <!-- 删除确认对话框 -->
    <DeleteConfirmDialog
      v-model="showDeleteConfirmDialog"
      :dimension="currentDimension"
      @confirm-delete="handleConfirmDelete"
      @only-disable="handleOnlyDisable"
      @export-and-delete="handleExportAndDelete"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh, ArrowDown } from "@element-plus/icons-vue";

// 组件导入
import StatisticsCards from "./components/StatisticsCards.vue";
import FilterPanel from "./components/FilterPanel.vue";
import DimensionTable from "./components/DimensionTable.vue";
import CreateEditDimensionDialog from "./components/CreateEditDimensionDialog.vue";
import DimensionDetailDialog from "./components/DimensionDetailDialog.vue";
import CopyDimensionDialog from "./components/CopyDimensionDialog.vue";
// import BatchOperationDialog from "./components/BatchOperationDialog.vue";
// import BatchResultDialog from "./components/BatchResultDialog.vue";
// import DimensionUsageDialog from "./components/DimensionUsageDialog.vue";
// import DeleteConfirmDialog from "./components/DeleteConfirmDialog.vue";

// API导入
import {
  getDimensionList,
  getDimensionStatistics,
  enableDimension,
  disableDimension,
  deleteDimension,
  batchUpdateOrder,
  getDimensionDetail,
} from "../../servers";

// 响应式数据
const statistics = ref({
  total_dimensions: 0,
  enabled_count: 0,
  disabled_count: 0,
  used_count: 0,
  total: 0,
  enabled: 0,
  disabled: 0,
});

const dimensionList = ref([]);
const originalList = ref([]); // 用于排序模式的原始数据
const filterForm = ref({
  name: "",
  code: "",
  template_id: "",
  status: "",
});

// 表格引用
const dimensionTableRef = ref();

// 状态控制
const statsLoading = ref(false);
const tableLoading = ref(false);
const actionLoading = ref(false);
const detailLoading = ref(false);
const sortMode = ref(false);
const autoSaveSort = ref(false);
const sortChanges = ref([]);
const selectedRows = ref([]);

// 对话框控制
const showCreateEditDialog = ref(false);
const showDetailDialog = ref(false);
const showCopyDialog = ref(false);
const showBatchConfirmDialog = ref(false);
const showBatchResultDialog = ref(false);
const showUsageDialog = ref(false);
const showDeleteConfirmDialog = ref(false);

// 当前操作的维度ID和数据
const currentDimensionId = ref<number | string>("");
const currentDimensionCode = ref("");
const currentDimension = ref<any>({});

// 批量操作相关
const batchOperation = ref("");
const batchResult = ref<any>({
  total: 0,
  success: 0,
  failed: 0,
  already: 0,
  details: [],
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
});

// 数据映射函数：将接口返回的数据映射为前端需要的格式
const mapDimensionData = (items: any[]) => {
  return items.map((item) => ({
    ...item,
    id: item.id,
    name: item.dimension_name || item.name,
    code: item.dimension_code || item.code,
    is_enabled:
      item.is_enabled !== undefined
        ? item.is_enabled
        : item.status === "启用"
        ? true
        : false,
    status:
      item.is_enabled !== undefined
        ? item.is_enabled
          ? "启用"
          : "禁用"
        : item.status || "禁用",
    sort_order: item.display_order || item.sort_order || 0,
    _switching: false, // 用于控制 switch 的 loading 状态
  }));
};

// 方法 - 获取统计数据
const fetchStatistics = async () => {
  statsLoading.value = true;
  try {
    const { data } = await getDimensionStatistics();
    // 兼容新旧数据结构
    statistics.value = {
      ...data,
      total: data.total_dimensions || data.total || 0,
      enabled: data.enabled_count || data.enabled || 0,
      disabled: data.disabled_count || data.disabled || 0,
      used_count: data.used_count || 0,
    };
  } catch (error) {
    ElMessage.error("获取统计数据失败");
  } finally {
    statsLoading.value = false;
  }
};

// 方法 - 获取维度列表
const fetchDimensionList = async () => {
  tableLoading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };

    // 映射筛选条件
    if (filterForm.value.name) {
      params.dimension_name = filterForm.value.name;
    }
    if (filterForm.value.code) {
      params.dimension_code = filterForm.value.code;
    }
    if (filterForm.value.template_id) {
      params.template_id = filterForm.value.template_id;
    }
    if (filterForm.value.status) {
      params.is_enabled = filterForm.value.status === "启用";
    }

    const { data } = await getDimensionList(params);
    const items = data.items || data.list || [];
    const mappedItems = mapDimensionData(items);
    dimensionList.value = mappedItems;
    originalList.value = JSON.parse(JSON.stringify(mappedItems));
    pagination.total = data.total || 0;
  } catch (error) {
    ElMessage.error("获取维度列表失败");
  } finally {
    tableLoading.value = false;
  }
};

// 事件处理 - 刷新
const handleRefresh = () => {
  fetchStatistics();
  fetchDimensionList();
};

// 事件处理 - 搜索
const handleSearch = (formData) => {
  filterForm.value = formData;
  pagination.currentPage = 1;
  fetchDimensionList();
};

// 事件处理 - 重置筛选
const handleReset = () => {
  filterForm.value = {
    name: "",
    code: "",
    template_id: "",
    status: "",
  };
  pagination.currentPage = 1;
  fetchDimensionList();
};

// 事件处理 - 分页
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchDimensionList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchDimensionList();
};

// 事件处理 - 选择行变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 事件处理 - 创建维度
const handleCreateDimension = () => {
  currentDimensionId.value = "";
  showCreateEditDialog.value = true;
};

// 事件处理 - 编辑维度
const handleEditDimension = async (id: number) => {
  currentDimensionId.value = id;
  await fetchDimensionDetailData(id);
  showCreateEditDialog.value = true;
};

// 事件处理 - 从详情页编辑
const handleEditFromDetail = async (id: number) => {
  showDetailDialog.value = false;
  // 如果详情数据已经存在，直接使用，否则重新获取
  if (!currentDimension.value || currentDimension.value.id !== id) {
    await fetchDimensionDetailData(id);
  }
  setTimeout(() => {
    currentDimensionId.value = id;
    showCreateEditDialog.value = true;
  }, 300);
};

// 事件处理 - 查看详情
const handleViewDetail = async (id: number) => {
  currentDimensionId.value = id;
  await fetchDimensionDetailData(id);
  showDetailDialog.value = true;
};

// 事件处理 - 复制维度
const handleCopyDimension = (id: number) => {
  currentDimensionId.value = id;
  showCopyDialog.value = true;
};

// 事件处理 - 从详情页复制
const handleCopyFromDetail = (id) => {
  showDetailDialog.value = false;
  setTimeout(() => {
    currentDimensionId.value = id;
    showCopyDialog.value = true;
  }, 300);
};

// 事件处理 - 启用维度
const handleEnableDimension = async (id: number, row?: any) => {
  // 如果传入了 row，设置切换状态
  if (row) {
    row._switching = true;
  } else {
  actionLoading.value = true;
  }

  try {
    const result = await enableDimension({ dimension_id: id });

    // 处理响应结果
    if (result.code === 2000) {
    ElMessage.success("维度启用成功");
    fetchDimensionList();
    fetchStatistics();
    } else if (result.code === 2001) {
      ElMessage.info("维度已经是启用状态");
      // 如果状态已经是启用，确保本地状态正确
      if (row) {
        row.is_enabled = true;
      }
    } else {
      ElMessage.error(result.message || "维度启用失败");
      // 操作失败，回滚状态
      if (row) {
        row.is_enabled = false;
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "维度启用失败");
    // 操作失败，回滚状态
    if (row) {
      row.is_enabled = false;
    }
  } finally {
    if (row) {
      row._switching = false;
    } else {
    actionLoading.value = false;
    }
  }
};

// 事件处理 - 禁用维度
const handleDisableDimension = async (id: number, row?: any) => {
  // 如果传入了 row，设置切换状态
  if (row) {
    row._switching = true;
  } else {
  actionLoading.value = true;
  }

  try {
    const result = await disableDimension({ dimension_id: id });

    // 处理响应结果
    if (result.code === 2000) {
    ElMessage.success("维度禁用成功");
    fetchDimensionList();
    fetchStatistics();
    } else if (result.code === 2001) {
      ElMessage.info("维度已经是禁用状态");
      // 如果状态已经是禁用，确保本地状态正确
      if (row) {
        row.is_enabled = false;
      }
    } else {
      ElMessage.error(result.message || "维度禁用失败");
      // 操作失败，回滚状态
      if (row) {
        row.is_enabled = true;
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "维度禁用失败");
    // 操作失败，回滚状态
    if (row) {
      row.is_enabled = true;
    }
  } finally {
    if (row) {
      row._switching = false;
    } else {
    actionLoading.value = false;
  }
  }
};

// 事件处理 - 删除维度
const handleDeleteDimension = async (id: number) => {
  try {
    await ElMessageBox.confirm(`确定要删除维度"${id}"吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const result = await deleteDimension({ dimension_id: id });
        if (result.code === 2000) {
          ElMessage.success("维度删除成功");
    fetchDimensionList();
    fetchStatistics();
        } else {
          ElMessage.error(result.message || "维度删除失败");
        }
      })
      .catch(() => {
        ElMessage.warning("取消删除");
      });
  } catch (error: any) {
    ElMessage.error(error?.message || "维度删除失败");
  }
};

// 事件处理 - 查看使用情况
const handleViewUsage = (code) => {
  currentDimensionCode.value = code;
  showUsageDialog.value = true;
};

// 批量操作处理
const handleBatchCommand = (command) => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要操作的维度");
    return;
  }

  batchOperation.value = command;
  showBatchConfirmDialog.value = true;
};

// 确认批量操作
const handleBatchConfirm = async () => {
  showBatchConfirmDialog.value = false;
  actionLoading.value = true;
  const ids = selectedRows.value.map((row) => row.id);

  try {
    let result;
    if (batchOperation.value === "enable") {
      result = await enableDimension({ dimension_ids: ids });
    } else if (batchOperation.value === "disable") {
      result = await disableDimension({ dimension_ids: ids });
    } else if (batchOperation.value === "delete") {
      // 批量删除需要逐个调用接口
      const deleteResults = [];
      for (const id of ids) {
        try {
          const deleteResult = await deleteDimension({ dimension_id: id });
          deleteResults.push(deleteResult);
        } catch (error) {
          deleteResults.push({ code: 5000, message: "删除失败", data: null });
        }
      }
      // 统计结果
      const successCount = deleteResults.filter((r) => r.code === 2000).length;
      const failedCount = deleteResults.length - successCount;
      result = {
        code: failedCount === 0 ? 2000 : 2001,
        message: `批量删除完成: 成功 ${successCount} 个, 失败 ${failedCount} 个`,
        data: {
          total: ids.length,
          success: successCount,
          failed: failedCount,
          details: deleteResults.map((r, index) => ({
            id: ids[index],
            status: r.code === 2000 ? "success" : "failed",
            message: r.message,
          })),
        },
      };
    }

    // 假设返回的结果结构包含操作统计
    batchResult.value = result?.data || {
      total: ids.length,
      success: ids.length,
      failed: 0,
      already: 0,
      details: [],
    };

    showBatchResultDialog.value = true;
    fetchDimensionList();
    fetchStatistics();
  } catch (error) {
    ElMessage.error(`批量${getOperationText(batchOperation.value)}失败`);
  } finally {
    actionLoading.value = false;
    selectedRows.value = [];
  }
};

// 获取操作文本
const getOperationText = (operation) => {
  const textMap = {
    enable: "启用",
    disable: "禁用",
    delete: "删除",
  };
  return textMap[operation] || "";
};

// 重试失败项
const handleRetryFailed = () => {
  showBatchResultDialog.value = false;
  const failedIds = batchResult.value.details
    .filter((item) => item.status === "failed")
    .map((item) => item.id);

  selectedRows.value = dimensionList.value.filter((row) =>
    failedIds.includes(row.id)
  );

  showBatchConfirmDialog.value = true;
};

// 排序模式处理
const toggleSortMode = () => {
  sortMode.value = !sortMode.value;
  if (sortMode.value) {
    // 进入排序模式时保存原始顺序
    originalList.value = JSON.parse(JSON.stringify(dimensionList.value));
    sortChanges.value = [];
  }
};

// 允许拖放
const allowDrop = () => {
  return true;
};

// 拖动结束处理
const handleDragEnd = (row, column, cell, event) => {
  // 记录排序变化
  const oldIndex = originalList.value.findIndex((item) => item.id === row.id);
  const newIndex = dimensionList.value.findIndex((item) => item.id === row.id);

  if (oldIndex !== newIndex) {
    // 更新排序号
    dimensionList.value.forEach((item, index) => {
      item.sort_order = index + 1;
    });

    // 记录变更
    const existingIndex = sortChanges.value.findIndex(
      (change) => change.id === row.id
    );
    if (existingIndex > -1) {
      sortChanges.value[existingIndex].newIndex = newIndex + 1;
    } else {
      sortChanges.value.push({
        id: row.id,
        name: row.name,
        oldIndex: oldIndex + 1,
        newIndex: newIndex + 1,
      });
    }

    // 自动保存
    if (autoSaveSort.value) {
      handleSaveSort();
    }
  }
};

// 取消排序更改
const handleCancelSort = () => {
  dimensionList.value = JSON.parse(JSON.stringify(originalList.value));
  sortChanges.value = [];
};

// 保存排序
const handleSaveSort = async () => {
  actionLoading.value = true;
  try {
    const orderData = dimensionList.value.map((item, index) => ({
      id: item.id,
      sort_order: index + 1,
    }));

    await batchUpdateOrder({ dimensions: orderData });
    ElMessage.success("排序保存成功");
    originalList.value = JSON.parse(JSON.stringify(dimensionList.value));
    sortChanges.value = [];
  } catch (error) {
    ElMessage.error("排序保存失败");
  } finally {
    actionLoading.value = false;
  }
};

// 获取维度详情数据
const fetchDimensionDetailData = async (id: number) => {
  detailLoading.value = true;
  try {
    const result = await getDimensionDetail({ dimension_id: id });
    if (result.code === 2000 && result.data) {
      currentDimension.value = result.data;
    } else {
      ElMessage.error(result.message || "获取维度详情失败");
      currentDimension.value = {};
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取维度详情失败");
    currentDimension.value = {};
  } finally {
    detailLoading.value = false;
  }
};

// 表单提交成功处理
const handleFormSuccess = () => {
  showCreateEditDialog.value = false;
  currentDimension.value = {};
  currentDimensionId.value = "";
  fetchDimensionList();
  fetchStatistics();
};

// 复制成功处理
const handleCopySuccess = () => {
  showCopyDialog.value = false;
  fetchDimensionList();
  fetchStatistics();
  ElMessage.success("维度复制成功");
};

// 删除确认处理
const handleConfirmDelete = async () => {
  showDeleteConfirmDialog.value = false;
  actionLoading.value = true;
  try {
    const result = await deleteDimension({
      dimension_id: currentDimension.value.id,
    });
    if (result.code === 2000) {
    ElMessage.success("维度删除成功");
    fetchDimensionList();
    fetchStatistics();
    } else if (result.code === 4004) {
      ElMessage.warning("维度不存在或已被删除");
      fetchDimensionList();
      fetchStatistics();
    } else {
      ElMessage.error(result.message || "维度删除失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "维度删除失败");
  } finally {
    actionLoading.value = false;
  }
};

// 仅禁用处理
const handleOnlyDisable = async () => {
  showDeleteConfirmDialog.value = false;
  actionLoading.value = true;
  try {
    await disableDimension({ dimension_id: currentDimension.value.id });
    ElMessage.success("维度已禁用");
    fetchDimensionList();
    fetchStatistics();
  } catch (error) {
    ElMessage.error("维度禁用失败");
  } finally {
    actionLoading.value = false;
  }
};

// 导出并删除处理
const handleExportAndDelete = async () => {
  // 先导出配置
  ElMessage.success("配置已导出");

  // 然后删除
  showDeleteConfirmDialog.value = false;
  actionLoading.value = true;
  try {
    const result = await deleteDimension({
      dimension_id: currentDimension.value.id,
    });
    if (result.code === 2000) {
    ElMessage.success("维度删除成功");
    fetchDimensionList();
    fetchStatistics();
    } else if (result.code === 4004) {
      ElMessage.warning("维度不存在或已被删除");
      fetchDimensionList();
      fetchStatistics();
    } else {
      ElMessage.error(result.message || "维度删除失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "维度删除失败");
  } finally {
    actionLoading.value = false;
  }
};

// 页面加载时初始化
onMounted(() => {
  fetchStatistics();
  fetchDimensionList();
});
</script>

<style scoped lang="scss">
.dimension-config-container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;

  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #1d2129;
    display: flex;
    align-items: center;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
}

.sort-mode-active {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #1890ff;
}

.sort-mode-notice {
  margin-bottom: 16px;
}

.sort-mode-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.sort-changes-card {
  margin-bottom: 16px;
  border-left: 4px solid #1890ff;

  .card-title {
    font-weight: 500;
    margin-bottom: 10px;
    color: #1d2129;
  }

  .changes-list {
    margin-bottom: 15px;
    padding-left: 5px;
  }

  .change-item {
    margin-bottom: 5px;
    font-size: 13px;
  }

  .auto-save-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 10px;
    border-top: 1px dashed #e5e6eb;
  }
}

.dimension-table-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.monospace-text {
  font-family: monospace;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
}

::v-deep .el-table__column--draggable {
  cursor: move;
}

::v-deep .el-table__row--drag-hover {
  background-color: #f5f7fa !important;
}
</style>
